package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.service.CategoryService;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 分类管理
 */
@RestController
@RequestMapping("category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /**
     * 新增分类
     *
     * @param category
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Category category) {
        //直接调用业务层操作数据库
        categoryService.save(category);
        return R.success("添加成功");
    }

    /**
     * 分页
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("page")
    public R<Page<Category>> page(int page, int pageSize, String name) {
        //创建分页对象
        Page<Category> categoryPage = new Page<>(page, pageSize);
        //分页查询
        categoryService.query()
                .like(StringUtils.isNotBlank(name), "name", name)
                .orderByAsc("sort")
                .orderByDesc("update_time")
                .page(categoryPage);
        return R.success(categoryPage);

    }

    /**
     * 删除分类
     * @param id
     * @return
     */
    @DeleteMapping()
    public R<String> deleteById(Long id){
        categoryService.deleteById(id);
        return R.success("删除成功");
    }

    /**
     * 修改
     * @param category
     * @return
     */
    @PutMapping
    public R<String>update(@RequestBody Category category){

        categoryService.updateById(category);
        return R.success("修改成功");
    }

    /**
     * 根据type类型查询分类列表
     * @param type
     * @return
     */
    @GetMapping("list")
    public R<List<Category>> list(Integer type){
        //调用业务层方法
        List<Category> list = categoryService.query()
                .eq(type != null, "type", type)
                .orderByAsc("sort")
                .orderByDesc("update_time")
                .list();
        //响应数据
        return  R.success(list);

    }


}
